import logging

from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import redis_store
from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue

@index_blue.route('/')
@user_login_data
def index():




    # 查询数据库 按照点击率显示前十条数据
    try:
        news_items = News.query.order_by(News.clicks.desc()).limit(10)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="数据库查询失败")

    # 将新闻对象列表转化成字典
    news_list = []
    for item  in news_items:
        news_list.append(item.to_dict())

    # 查询数据库，查出分类
    try:
        news_category = Category.query.all()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库查询失败")

    news_category_item = []
    for i in news_category:
        news_category_item.append(i.to_dict())


    data = {
        "user_info":g.user.to_dict() if g.user else "",
        "news_list":news_list,
        "news_category_item":news_category_item
    }

    return render_template("news/index.html",data=data,news_list=news_list,news_category_item=news_category_item)

#设置网站logo,地址是/favicon.ico
@index_blue.route('/favicon.ico')
def get_web_lofo():


    return current_app.send_static_file("news/favicon.ico")
#获取首页新闻列表数据
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据

@index_blue.route("/newslist")
def get_newslist():
    """
    思路分析:
    1.获取参数
    2.转换参数类型
    3.查询数据库
    4.获取到分页对象中的内容
    5.将对象列表,转成字典列表
    6.返回响应,携带数据
    :return:
    """
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)

    # 2.转换参数类型
    try:
        page = int(page)

        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10

    # 3.查询数据库
    try:

      #  判断分类编号是否不等于1
        filters = []
        if cid != "1":
            filters.append(News.category_id == cid)

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻失败")

    # 4.获取到分页对象中的内容
    currentPage = paginate.page
    totalPage = paginate.pages
    items = paginate.items

    # 5.将对象列表,转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    # 6.返回响应,携带数据
    return jsonify(errno=RET.OK, errmsg="查询成功", totalPage=totalPage, currentPage=currentPage, newsList=news_list)

